package org.edu.modules.stu.zhsz.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.dto.ExcelPo;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.common.utils.PoiUtils;
import org.edu.modules.stu.base.dto.VeBaseStudentDto;
import org.edu.modules.stu.base.service.VeBaseStudentService;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.entity.VeBaseTeacher;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.edu.modules.stu.common.service.VeBaseTeacherService;
import org.edu.modules.stu.zhsz.dto.VeStuCheckItemDto;
import org.edu.common.dto.AllDto;
import org.edu.modules.stu.zhsz.entity.VeStuCheckItem;
import org.edu.modules.stu.zhsz.service.VeStuCheckItemService;
import org.edu.common.api.vo.Result;
import org.edu.common.base.PageDto;
import org.edu.common.dto.StatusDto;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Api(tags = {"项目表"})
@RestController
@RequestMapping("/stu/veStuCheckItem")
@Slf4j
public class VeStuCheckItemController{

    @Autowired
    private VeStuCheckItemService veStuCheckItemService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Autowired
    private VeBaseTeacherService veBaseTeacherService;

    @Autowired
    private VeBaseStudentService veBaseStudentService;

    @ApiOperation("分页查询项目表")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageDto<VeStuCheckItem> page) {
        QueryWrapper<VeStuCheckItem> queryWrapper =  page.buildQueryWrapper(VeStuCheckItem.class);
        return Result.OK(veStuCheckItemService.page(page, queryWrapper));
    }

    /**
     * 查询所有
     */
    @ApiOperation("查询所有")
    @PostMapping("/all")
    public Result<?> all(@RequestBody AllDto<VeStuCheckItem> page) {
        QueryWrapper<VeStuCheckItem> queryWrapper = page.buildQueryWrapper(VeStuCheckItem.class);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        if (appUser.getUserType().contains("2")) {
            //如果用户类型是2，为学生账号
            //查学生信息
            VeBaseStudentDto veBaseStudentDto = veBaseStudentService.findDtoByXh(appUser.getUserId());
            queryWrapper.apply("  id in( select item_id from ve_stu_check_student where stu_id={0} )  ",
                    veBaseStudentDto.getId());
        }else if (appUser.getUserType().contains("1")) {
            //如果用户类型是1，为教师账号
            queryWrapper.apply("  id in( select item_id from ve_stu_check_judger where judge_user_id={0} )  ",
                    appUser.getUserId());
        }

        List<VeStuCheckItem> list = veStuCheckItemService.listByWrapper(queryWrapper);

        return Result.OK(list);
    }

    @ApiOperation("导出数据）")
    @PostMapping("/export")
    public Result<?> export(@RequestBody PageDto<VeStuCheckItem> page, HttpServletResponse resp) {
        QueryWrapper<VeStuCheckItem> queryWrapper =  page.buildQueryWrapper(VeStuCheckItem.class);
        List<ExcelPo> list = new ArrayList<>();
        list.add(new ExcelPo("项目名称","name"));
        list.add(new ExcelPo("开始时间","startTime"));
        list.add(new ExcelPo("结束时间","endTime"));
        list.add(new ExcelPo("状态（0：禁用，1：启用）","status"));
        list.add(new ExcelPo("项目负责人","userId"));
        list.add(new ExcelPo("","userName"));
        list.add(new ExcelPo("是否删除（0：否，1：是）","isDelete"));
                PoiUtils.downloadFile(resp,veStuCheckItemService.page(page, queryWrapper).getRecords(),list);
        return Result.OK();
    }

    @AutoLog(value = "项目表-分页列表查询")
    @ApiOperation(value="项目表-分页列表查询", notes="项目表-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(VeStuCheckItem entity,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeStuCheckItem> queryWrapper = QueryGenerator.initQueryWrapper(entity, req.getParameterMap());
        PageDto<VeStuCheckItem> page = new PageDto<VeStuCheckItem>(pageNo, pageSize);
        IPage<VeStuCheckItem> pageList = veStuCheckItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "通过id查询")
    @ApiOperation(value="通过id查询", notes="通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        VeStuCheckItem dto = veStuCheckItemService.findDtoById(id);
        if(dto==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dto);
    }

    @AutoLog(value = "添加")
    @ApiOperation(value="添加", notes="添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeStuCheckItemDto dto) {
        veStuCheckItemService.insertOrUpdate(dto , true);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "编辑")
    @ApiOperation(value="编辑", notes="编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeStuCheckItemDto dto) {
        veStuCheckItemService.insertOrUpdate(dto , false);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量删除")
    @ApiOperation(value="批量删除", notes="批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        veStuCheckItemService.delete(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "更新状态")
    @ApiOperation(value="更新状态")
    @PostMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody StatusDto statusDto) {
        LambdaUpdateWrapper<VeStuCheckItem> updateWrapper = new LambdaUpdateWrapper<>();
        if(statusDto.getIds()!=null && statusDto.getIds().size()>0){
       //     updateWrapper.set(VeStuCheckItem::getStatus,statusDto.getStatus());
            updateWrapper.in(VeStuCheckItem::getId,statusDto.getIds());
            veStuCheckItemService.update(updateWrapper);
            return Result.OK("批量更新成功!");
        }else{
            return Result.error("未选择!");
        }
    }




}
